package com.ptswitch.material.web.action;

import org.springframework.stereotype.Controller;

import com.hxzon.util.MD5;
import com.ptswitch.material.model.Uzer;

@Controller("welcomeAction")
public class WelcomeAction extends ActionSupport{

	private String rand;
	private Uzer user;

	public String welcome() {
		visitor();
		return "index";
	}

	public boolean existName() {
		return userSer.existName(user.getUsername());
	}

	public String toLogin() {
		user = null;
		logout2();
		return "login";
	}

	public String login() {
		logout2();
		// if (!(Check.checkRand(this.rand))) {
		// Check.putMsg("验证码出错");
		// return "login";
		// }
		if (userSer.countAll() == 0) {
			this.user.setPassword(MD5.toMD5(this.user.getUsername() + this.user.getPassword()));
			user.setAdminGrade(0);
			userSer.save(user);
			login(user);
			putMsg("登陆成功。您是第一个用户，已自动升级为管理员");
			return "index";
		}
		Uzer user = userSer.getByNameAndPassword(this.user.getUsername(),this.user.getPassword(),true);
		if (user!=null) {
			login(user);
			putMsg("登陆成功");
			logger.debug("login:" + user.getUsername());
			return "index";
		}
		putMsg("用户名或者密码错误");
		return "login";
	}

	public String logout() {
		logout2();
		putMsg("你已退出登陆");
		logger.debug("logout:" + user.getUsername());
		return "index";
	}

	// edit
	public String toUpdate() {
//		mustLogin();
//		user = visitor();
//		return "update";
		return "index";
	}

	// save

	public String update() {
//		mustLogin();
//		userSer.save(user);
//		login(user);
//		return "rDisplay";
		materialSer.existPcbDecal(id);
		return "index";
	}

	// password
	public String toChangePassword() {
		mustLogin();
		user = null;
		return "changePassword";
	}

	public String changePassword() {
		mustLogin();
		user.setPassword(MD5.toMD5(visitor().getUsername() + user.getPassword()));
		if (visitor().getPassword().equals(user.getPassword())) {
			visitor().setPassword(MD5.toMD5(visitor().getUsername() + user.getUsername()));
			// user.username is new password
			userSer.save(visitor());
			putMsg("修改密码成功");
			return "display";
		} else {
			putMsg("原有密码不正确");
			return "changePassword";
		}
	}

	// get and set
	public Uzer getUser() {
		if (user == null) {
			user = new Uzer();
		}
		return user;
	}

	public String getRand() {
		return rand;
	}

	public void setRand(String rand) {
		this.rand = rand;
	}

}
